package util

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"gopkg.in/yaml.v3"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"reflect"
	"runtime"
	"strings"
)

// 加载配置文件
func LoadConfig(fileName, caseSelect string, request interface{}) (err error) {

	filePath := GenPath(fileName, "config")

	b, err := ioutil.ReadFile(filePath)

	fmt.Println(err)
	if err != nil {
		return
	}

	ymlContent := make(map[string]string, 0)
	err = yaml.Unmarshal(b, &ymlContent)
	if err != nil {
		return
	}

	//填入数据
	if r, ok := ymlContent[caseSelect]; ok {
		buf := bytes.NewBufferString(r)
		decoder := json.NewDecoder(buf)
		decoder.UseNumber()
		err = decoder.Decode(request)
		fmt.Println(reflect.TypeOf(request))
		if err != nil {
			return
		}
	} else {
		return errors.New("key not exist")
	}
	return
}

// 获得配置路径
func GenPath(fileName, folderName string) string {
	filePath := ""

	path := getCurrentAbPath02()

	prePath := filepath.Join(path, "../")

	//拼写路径
	filePath = fmt.Sprintf("%s/%s/%s", prePath, folderName, fileName)
	//relpath := ""
	//filepath.Rel(filePath, relpath)

	fmt.Println("path测试", filePath)
	return filePath
}

// 获取绝对路径
func getCurrentAbPath02() string {
	//拿目录
	// 获取当前执行文件所在的文件夹路径
	dir, err := os.Getwd()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	tmpDir, _ := filepath.EvalSymlinks(os.TempDir())
	if strings.Contains(dir, tmpDir) {
		return getCurrentAbPathByCaller()
	}
	return dir
}

// 由于拉取镜像代码的缘故，所以需要有另一套路径获取方式
func getCurrentAbPath() string {
	//拿目录
	dir := getCurrentAbPathByExecutable()
	tmpDir, _ := filepath.EvalSymlinks(os.TempDir())
	if strings.Contains(dir, tmpDir) {
		return getCurrentAbPathByCaller()
	}
	return dir
}

// 获取当前执行文件绝对路径
func getCurrentAbPathByExecutable() string {
	exePath, err := os.Executable()
	if err != nil {

		fmt.Println(err)
	}
	res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
	return res
}

// 获取当前执行文件绝对路径（go run）
func getCurrentAbPathByCaller() string {
	var abPath string
	_, filename, _, ok := runtime.Caller(0)
	if ok {
		abPath = path.Dir(filename)
	}
	return abPath
}
